@ECHO OFF
SETLOCAL

REM 设置当前脚本所在的目录为变量
SET "SCRIPT_DIR=%~dp0"

REM 定义安装目录
SET "INSTALL_DIR=%SCRIPT_DIR%install\qt_5.14.2_msvc2017x64_static"

REM 定义OpenSSL前缀路径
SET "OPENSSL_PREFIX=%SCRIPT_DIR%install\OpenSSL_1_1_1dx64_static"

REM 调用Visual Studio 2017 Enterprise的vcvarsall.bat来设置环境变量
CALL "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x64
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to set up Visual Studio 2017 Enterprise environment
    PAUSE
    EXIT /B 1
)

REM 将Python2.7.18和Scripts目录添加到PATH
SET "PATH=%SCRIPT_DIR%Python2.7.18;%SCRIPT_DIR%Python2.7.18\Scripts;%PATH%"

REM 检查Python是否可用
python -V
IF %ERRORLEVEL% NEQ 0 (
    ECHO Python is not available. Please check your Python installation.
    PAUSE
    EXIT /B 1
)

REM 将Ruby33-x64目录添加到PATH
SET "PATH=%SCRIPT_DIR%Ruby33-x64\bin;%PATH%"

REM 检查Ruby是否可用
ruby -v
IF %ERRORLEVEL% NEQ 0 (
    ECHO Ruby is not available. Please check your Ruby installation.
    PAUSE
    EXIT /B 1
)

REM 将Strawberry Perl相关的目录添加到PATH
SET "PATH=%SCRIPT_DIR%Strawberry5.38.2.2\c\bin;%SCRIPT_DIR%Strawberry5.38.2.2\perl\site\bin;%SCRIPT_DIR%Strawberry5.38.2.2\perl\bin;%PATH%"

REM 检查Perl是否可用
perl -v
IF %ERRORLEVEL% NEQ 0 (
    ECHO Perl is not available. Please check your Perl installation.
    PAUSE
    EXIT /B 1
)

REM 将jom_1_1_4的目录添加到PATH
SET "PATH=%SCRIPT_DIR%jom_1_1_4;%PATH%"

REM 输出更新后的PATH以确认
ECHO Updated PATH: %PATH%

REM 切换到Qt源码目录
CD /D "%SCRIPT_DIR%qt-everywhere-src-5.14.2"
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to change directory to qt-everywhere-src-5.14.2
    PAUSE
    EXIT /B 1
)

REM 定义构建目录
SET "BUILD_DIR=%SCRIPT_DIR%build\qt_5.14.2_msvc2017x64_static"

REM 创建构建目录（如果不存在）
IF NOT EXIST "%BUILD_DIR%" MKDIR "%BUILD_DIR%"

REM 切换到构建目录
CD /D "%BUILD_DIR%"
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to change directory to %BUILD_DIR%
    PAUSE
    EXIT /B 1
)

REM 运行 configure 脚本
CALL "%SCRIPT_DIR%configure.bat" %SCRIPT_DIR% %INSTALL_DIR% %OPENSSL_PREFIX%
IF %ERRORLEVEL% NEQ 0 (
    ECHO Configuration failed with error code %ERRORLEVEL%
    ECHO Check the output above for more details.
    PAUSE
    EXIT /B 1
) ELSE (
    ECHO Configuration succeeded.
)

REM 使用jom进行并行编译
ECHO Running jom...
jom -j 16
IF %ERRORLEVEL% NEQ 0 (
    ECHO jom failed with error code %ERRORLEVEL%
    ECHO Check the output above for more details.
    PAUSE
    EXIT /B 1
) ELSE (
    ECHO jom succeeded.
)

REM 使用nmake进行安装
ECHO Running nmake install...
nmake install
IF %ERRORLEVEL% NEQ 0 (
    ECHO Installation failed with error code %ERRORLEVEL%
    ECHO Check the output above for more details.
    PAUSE
    EXIT /B 1
) ELSE (
    ECHO Installation succeeded.
)

REM 清理构建目录
ECHO Cleaning up build directory...
CD /D "%SCRIPT_DIR%"
RD /S /Q "%BUILD_DIR%"
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to clean up build directory
    PAUSE
    EXIT /B 1
) ELSE (
    ECHO Build directory cleaned up successfully.
)

ECHO Qt 5.14.2 (both Release and Debug) has been successfully built and installed.

PAUSE
ENDLOCAL